package com.molinari.coding.commands;

import java.util.HashMap;

import android.content.Context;

import com.molinari.androidstructure.command.AbstractCommand;
import com.molinari.androidstructure.data.db.IDao;
import com.molinari.androidstructure.data.db.IOggettoEntita;
import com.molinari.coding.R;
import com.molinari.coding.dati.domain.IUtenti;
import com.molinari.coding.dati.domain.Utenti;
import com.molinari.coding.dati.domain.cache.CacheUtenti;
import com.molinari.coding.dati.domain.dao.WrapUtenti;

public class CommandInserisciUtente extends AbstractCommand {

	final private IOggettoEntita entita;
	final private IDao wrap;
	private final HashMap<String, IOggettoEntita> mappaCache;

	public CommandInserisciUtente(Context context, final IUtenti entita) {
		final CacheUtenti cache = CacheUtenti.getSingleton();
		mappaCache = (HashMap<String, IOggettoEntita>) cache.getCache();
		wrap = new WrapUtenti(context);
		this.entita =  entita.getEntita();
	}

	@Override
	public boolean execute() {
		if (entita instanceof Utenti) {
			try {
				if (wrap.insert(entita)) {
					mappaCache.put(entita.getIdEntita(), entita);
					return true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	@Override
	public boolean unExecute() {
		if (entita instanceof Utenti) {
			try {
				if (wrap.delete(Integer.parseInt(entita.getIdEntita()))) {
					mappaCache.remove(entita.getIdEntita());
					return true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	@Override
	public String toString() {
		return "Inserito Utente " + ((Utenti)entita).getNomeEntita();
	}
}
